﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace AviagePortal.Layouts.AviagePortal
{
    public partial class CopyItem : IHttpHandler
    {
        /*
         Check if a field is a built-in field or not:

        1. Check if the field is a built-in field: SPBuiltInFieldId.Contains(field.Id)
        2. Check on the SPField.SourceId (from MSDN):

        Using ECMAScript Client Object Model from ECB Custom Actions 

        Pasted from <http://pholpar.wordpress.com/2011/04/08/using-ecmascript-client-object-model-from-ecb-custom-actions/> 

        http://msstoresp12013/sites/ap/_layouts/15/AviagePortal/CopyItem.ashx 
         */

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            context.Response.ContentType = "application/json";
            string jsonResult = string.Empty;
            try
            {
                string listId = context.Request.QueryString["listId"];
                string itemId = context.Request.QueryString["itemId"];
                SPContext currentContext = SPContext.Current;
                SPWeb web = SPContext.Current.Web;
                SPList currentList = web.Lists[new Guid(listId)];
                string editFormUrl = currentList.DefaultEditFormUrl;
                SPListItem newItem = currentList.Items.Add();
                SPListItem copyItem = currentList.GetItemById(int.Parse(itemId));
                foreach (SPField field in currentList.Fields)
                {
                    if ((!SPBuiltInFieldId.Contains(field.Id) || field.Id.ToString() == SPBuiltInFieldId.Title.ToString()) && !field.ReadOnlyField)
                    {
                        newItem[field.Id] = copyItem[field.Id];

                    }
                }

                web.AllowUnsafeUpdates = true;
                newItem.Update();
                int newItemId = newItem.ID;
                jsonResult = jsonSerializer.Serialize(new CopyResult() { NewItemId = newItemId, UpdateFormUrl = editFormUrl });
                
            }
            catch (Exception ex)
            {
                jsonResult = jsonSerializer.Serialize(new CopyResult() { ErrorMessage=ex.Message, ErrorDetail= ex.StackTrace});
            }

            context.Response.Write(jsonResult);
        }
    }
}
